package socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import service.ServerAction;
//[V] This class should provide delivering of messages, but I didn't test it.
public class MessageDeliver extends Thread {
	
	private Socket connection = null;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private String message;
	private List<Connection> deliveryList = new ArrayList<Connection>();
	
	public MessageDeliver(Socket connection, ObjectOutputStream out, ObjectInputStream in, String message) {
		this.connection = connection;
		this.out = out;
		this.in = in;
		this.message = message;
	}
	
	public void run() {
		try {
			
			deliveryList = createDeliveryList();
			
			while (!deliveryList.isEmpty()) {
				for (Connection con : deliveryList) {
					if (ChatServer.connections.contains(con)) {
						if (!ChatServer.connections.get(ChatServer.connections.indexOf(con)).busy) {
							ServerAction serverAction = new ServerAction
							(ChatServer.connections.get(ChatServer.connections.indexOf(con)).out, in);
							serverAction.send(message);
							deliveryList.remove(con);
						}
					}
					else {
						deliveryList.remove(con);
					}
					this.wait(1); //[V] This string should be changed (may be sleep) otherwise thread must own this object's monitor
				}
	
			}
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		
	}
	//[V] This method creates new object which contains list of sockets where messages should be delivered
	private List<Connection> createDeliveryList() throws SocketException {
		List<Connection> delivery = new ArrayList<Connection>();
		for (Connection con : ChatServer.connections)
			if (con.connection.getKeepAlive() && (con.connection != this.connection)) {
				delivery.add(new Connection(con.connection,con.out,con.in));
			}
					
		return delivery;		
	}

}
